<?php

namespace app\core\controller;

use think\Controller;
use think\facade\Cache;

class File extends Controller
{

    public function index()
    {
        $id = 1;

        model('Picture')->thumb($id, 400, 500);

        exit;

        $picture = model('Picture')->getPicture($id);


        dump($picture->rpath);
        $image = \think\Image::open($picture->rpath);
        dump($image);
        echo '<img src="' . $picture->path . '">';

    }


    public function uploadImage()
    {
        $save_path = 'uploads/picture';
        $file = request()->file('image');
        $md5 = $file->md5();

        $pictureModel = model('Picture');
        $check = $pictureModel->checkPictureExist($md5);
        if ($check) {
            $picture = $pictureModel->getSimplePicture($check);
            return json(['msg' => '上传成功~', 'code' => 1, 'data' => $picture]);
        }

        $info = $file->rule(function () {
            return date('Y-m-d') . '/' . uniqid();
        })->move($save_path);

        $path = $save_path . '/' . $info->getSaveName();
        if ($info) {
            $driver = 'local';
            $ab_path = $path;
            $size = getimagesize($ab_path);
            $pic['driver'] = $driver;
            $pic['path'] = $path;
            $pic['md5'] = $info->md5();
            $pic['sha1'] = $info->sha1();
            $pic['width'] = $size[0];
            $pic['height'] = $size[1];
            $pic['ext'] = $size[2];
            $pic['size'] = $info->getSize();
            $pic['extra'] = json_encode($size);
            $id = $pictureModel->addPicture($pic);
            $picture = $pictureModel->getSimplePicture($id);

            return json(['msg' => '上传成功~', 'code' => 1, 'data' => $picture]);

        } else {
            // 上传失败获取错误信息
            return json(['msg' => '上传失败~', 'code' => 0, 'data' => $file->getError()]);

        }
    }

    public function cropAvatar()
    {
        $picture_id = input('post.picture_id', 0, 'intval');
        $crop = input('post.crop', '', 'text');

        $uid = is_login();
        $crop = json_decode($crop, true);
        $pictureModel = model('core/Picture');
        $picture = $pictureModel->getPicture($picture_id);

        $crop['x'] = $crop['x'] * $picture['width'];
        $crop['y'] = $crop['y'] * $picture['height'];
        $crop['w'] = $crop['w'] * $picture['width'];
        $crop['h'] = $crop['h'] * $picture['height'];
        $path = $pictureModel->crop($picture_id, $crop);
        model('user/User')->updateUserInfo($uid, ['avatar' => $path]);

        $pictureModel->thumbByPath($path, 64, 64);
        $pictureModel->thumbByPath($path, 128, 128);
        $pictureModel->thumbByPath($path, 256, 256);

        Cache::rm('user_' . $uid);

        return json(['msg' => '上传成功~', 'code' => 1, 'data' => ['path' => $path]]);
    }


}
